package tool

import (
	"fmt"
	"net/url"

	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
)

func NewJson() *json {
	return &json{}
}

type json struct {
	json *gjson.Json
}

func (r *json) FromJson(source string) *json {
	r.json = gjson.New(source)

	return r
}
func (r *json) ToJson() string {
	return r.json.MustToJsonIndentString()
}
func (r *json) FromQueryParameters(source string) *json {
	items, err := url.ParseQuery(source)
	if err != nil {
		panic(err)
	}

	result := g.Map{}
	for index, item := range items {
		if len(item) == 1 {
			result[index] = item[0]
		} else {
			result[index] = item
		}
	}

	r.json, err = gjson.DecodeToJson(result)
	if err != nil {
		panic(err)
	}

	return r
}
func (r *json) ToQueryParameters() string {
	var result []string

	for index, item := range r.json.Map() {
		result = append(result, fmt.Sprintf("%s=%s", index, item))
	}

	return gstr.Implode("&", result)
}
func (r *json) FromPostman(source string) *json {
	result := g.Map{}

	items := gstr.Explode("\n", source)
	for _, item := range items {
		temp := gstr.Explode(":", item)
		result[temp[0]] = temp[1]
	}

	var err error
	r.json, err = gjson.DecodeToJson(result)
	if err != nil {
		panic(err)
	}

	return r
}
func (r *json) ToPostman() string {
	var result []string

	for index, item := range r.json.Map() {
		result = append(result, fmt.Sprintf("%s:%s", index, item))
	}

	return gstr.Implode("\n", result)
}
